package com.gokzzz.killdemo.controller;

import com.gokzzz.killdemo.service.KillService;
import com.gokzzz.killdemo.service.SkuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author gokzzz
 * @date 2022-09-10 11:34
 */
@Slf4j
@RestController
public class KillController {
    @Resource
    private KillService killService;
    @Resource
    private SkuService skuService;

    @GetMapping("/initSKU/{num}")
    public String initSKU(@PathVariable Long num) {
        skuService.initSku(num);
        return "初始化库存，库存为：" + skuService.selectSku();
    }

    @GetMapping("/kill")
    public List<String> kill() {
        //抢到商品的用户
        List<String> usersByKill = new ArrayList<>();
        //构造很多用户
        log.info("开始构造10W个用户");
        List<String> users = new ArrayList<>();
        for (int i = 1; i <= 100000; i++) {
            users.add("【Gok-" + i + "】");
        }
        log.info("构造10W个用户完毕，开始秒杀");
        //模拟开抢
        users.parallelStream().forEach(user -> {
            String userByKill = killService.kill(user);
            if (userByKill != null && userByKill.length() > 0) {
                usersByKill.add(userByKill);
            }

        });
        log.info("秒杀结束，用户列表为：{}", usersByKill);
        return usersByKill;
    }

}
